/**
 * @BelongsProject: hmall-micro
 * @BelongsPackage: com.hmall.common.interceptor
 * @Author: 王明天
 * @CreateTime: 2025/2/9 13:37
 * @Description: UserInfoInterceptor
 */
package com.hmall.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class UserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头中的用户信息
        String userInfo = request.getHeader("user-info");

        //判断用户信息是否为空
        if(StrUtil.isNotBlank(userInfo)){

            //不为空，设置到线程中
            UserContext.setUser(Long.parseLong(userInfo));
        }

        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //调用系统提供的方法，移出存在线程中的用户信息
        UserContext.removeUser();
    }
}
